###############################################################################
# SuperLinks                                                                  #
# Copyright (c) 2000-2007 Greg Nolle (http://greg.nolle.co.uk)                #
###############################################################################
# This program is free software; you can redistribute it and/or modify it     #
# under the terms of the GNU General Public License as published by the Free  #
# Software Foundation; either version 2 of the License, or (at your option)   #
# any later version.                                                          #
#                                                                             #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       #
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for   #
# more details.                                                               ##                                                                             #
# You should have received a copy of the GNU General Public License along     #
# with this program; if not, write to the Free Software Foundation, Inc.,     #
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                 #
###############################################################################
# ControlPanel/RemoveCategories.pm.pl -> RemoveCategories module              #
###############################################################################
# DON'T EDIT BELOW UNLESS YOU KNOW WHAT YOU'RE DOING!                         #
###############################################################################
package CP::RemoveCategories;

BEGIN { require "System.pm.pl"; import System qw($SYSTEM); }
BEGIN { require "General.pm.pl"; import General qw($GENERAL); }
require "Error.pm.pl";
require "Standard.pm.pl";
require "Authenticate.pm.pl";
require "StaticPages.pm.pl";

use strict;

require "ControlPanel/Output/RemoveCategories.pm.pl";

sub new {
  my ($class) = @_;
  my $self    = {};
  return bless($self, $class);
}

sub DESTROY { }

###############################################################################
# show subroutine
sub show {
  my $self = shift;
  my %in = (DB => undef, @_);

  #----------------------------------------------------------------------#
  # Authenticating...                                                    #
  
  &Authenticate::CP(DB => $in{'DB'}, ACTION => "CATEGORIES_REMOVE");

  #----------------------------------------------------------------------#
  # Checking fields...                                                   #

  my @CID = $SL::CGI->param('CID');

  if (scalar(@CID) < 1) {
    &Error::Error("CP", MESSAGE => "You didn't specify any Category IDs (CID)");
  }

  #----------------------------------------------------------------------#
  # Getting data...                                                      #

  my ($Categories, $CategoriesIndex) = $in{'DB'}->Query(
    TABLE   => "Categories",
    SORT    => "FULL_TITLE",
    BY      => "A-Z"
  );

  my %INPUT;
  
  $INPUT{'CATEGORIES'}    = $Categories;
  $INPUT{'CATEGORIES_IX'} = $CategoriesIndex;

  #----------------------------------------------------------------------#
  # Printing page...                                                     #

  my $Skin = Skin::CP::RemoveCategories->new();

  &Standard::PrintHTMLHeader();
  print $Skin->show(input => \%INPUT);
  
  return 1;
}

###############################################################################
# do subroutine
sub do {
  my $self = shift;
  my %in = (DB => undef, @_);

  #----------------------------------------------------------------------#
  # Authenticating...                                                    #

  &Authenticate::CP(DB => $in{'DB'}, ACTION => "CATEGORIES_REMOVE");

  #----------------------------------------------------------------------#
  # Checking fields...                                                   #

  my @CID = $SL::CGI->param('CID');

  if (scalar(@CID) < 1) {
    &Error::Error("CP", MESSAGE => "You didn't specify any Category IDs (CID)");
  }
  
  if (
    $SL::QUERY{'FORM_ACTION'} eq "" ||
    ($SL::QUERY{'FORM_ACTION'} eq "MOVE" && $SL::QUERY{'FORM_MOVE'} eq "")
  ) {
    $self->show(DB => $in{'DB'});
    return 1;
  }

  #----------------------------------------------------------------------#
  # Deleting data...                                                     #

  my ($Categories, $CategoriesIndex) = $in{'DB'}->Query(TABLE => "Categories");

  my @SubCategories;
  CATEGORY: foreach my $category (@{ $Categories }) {
    foreach my $id (@CID) {
      my $cat = $Categories->[$CategoriesIndex->{$id}];
      next CATEGORY unless ($category->{'ROOT'} =~ /^$cat->{'ROOT'},$cat->{'ID'}/);
      next CATEGORY if ($category->{'ID'} == $id);
    }
    push(@SubCategories, $category);
  }

  my $StaticPages = StaticPages->new(DB => $in{'DB'});
  
  foreach my $id (@CID) {
    my $category = $Categories->[$CategoriesIndex->{$id}];
    $StaticPages->Update(TYPE => "Category", INPUT => $category, CHILDREN => 1)
      || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
  }

  if ($SL::QUERY{'FORM_ACTION'} eq "MOVE") {
    my ($Resources, $ResourcesIndex) = $in{'DB'}->Query(
      TABLE   => "Resources",
      WHERE   => {
        CATEGORY  => \@CID
      },
      MATCH   => "ANY"
    );
    
    my $counter;
    foreach my $resource (@{ $Resources }) {
      (
        $in{'DB'}->Update(
          TABLE   => "Resources",
          VALUES  => {
            CATEGORY  => $SL::QUERY{'FORM_MOVE'}
          },
          KEY     => $resource->{'ID'}
        )
      ) || &Error::Error("CP", MESSAGE => "Error updating record. $in{'DB'}->{'ERROR'}");
    
      $counter++ if ($resource->{'STATUS'});
    }
    
    if ($counter) {
      (
        $in{'DB'}->Update(
          TABLE   => "Categories",
          VALUES  => {
            RESOURCES => "\${RESOURCES}+$counter"
          },
          KEY     => $SL::QUERY{'FORM_MOVE'}
        )
      ) || &Error::Error("CP", MESSAGE => "Error updating record. $in{'DB'}->{'ERROR'}");
    }
    
    my @root = split(/,/, $Categories->[$CategoriesIndex->{$SL::QUERY{'FORM_MOVE'}}]->{'ROOT'});
    push(@root, $SL::QUERY{'FORM_MOVE'});
    
    foreach my $category (@SubCategories) {
      my @oldroot = split(/,/, $category->{'ROOT'});
      my @newroot = @root;
      push(@newroot, @oldroot[($#root + 1)..$#oldroot]) if (scalar(@oldroot[($#root + 1)..$#oldroot]) >= 1);
      
      my %VALUES;
      $VALUES{'ROOT'} = join(",", @newroot);
      
      foreach my $id (@newroot) {
        next if ($id == 0);
        $VALUES{'FULL_TITLE'} .= $Categories->[$CategoriesIndex->{$id}]->{'TITLE'}." / ";
      }
      $VALUES{'FULL_TITLE'} .= $category->{'TITLE'};
      
      (
        $in{'DB'}->Update(
          TABLE   => "Categories",
          VALUES  => \%VALUES,
          KEY     => $category->{'ID'}
        )
      ) || &Error::Error("CP", MESSAGE => "Error updating record. $in{'DB'}->{'ERROR'}");
    }

    (
      $in{'DB'}->Delete(
        TABLE   => "Categories",
        KEYS    => \@CID
      )
    ) || &Error::Error("CP", MESSAGE => "Error deleting records. $in{'DB'}->{'ERROR'}");
    
    $StaticPages->Update(TYPE => "Category", INPUT => $Categories->[$CategoriesIndex->{$SL::QUERY{'FORM_MOVE'}}])
      || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
  } else {
    my (@subcategories, @resources, @rates, @reviews);
    
    @subcategories = &Standard::MapArray("\${ID}", \@SubCategories);
    
    my ($Resources, $ResourcesIndex) = $in{'DB'}->Query(
      TABLE   => "Resources",
      WHERE   => {
        CATEGORY => [@CID, @subcategories]
      },
      MATCH   => "ANY"
    );
    @resources = &Standard::MapArray("\${ID}", $Resources);
    
    if (scalar(@resources) >= 1) {
      my ($Rates, $RatesIndex) = $in{'DB'}->Query(
        TABLE   => "Rates",
        WHERE   => {
          LID => \@resources
        },
        MATCH   => "ANY"
      );
      @rates = &Standard::MapArray("\${ID}", $Rates);
    
      my ($Reviews, $ReviewsIndex) = $in{'DB'}->Query(
        TABLE   => "Reviews",
        WHERE   => {
          LID => \@resources
        },
        MATCH   => "ANY"
      );
      @reviews = &Standard::MapArray("\${ID}", $Reviews);
    }
    
    (
      $in{'DB'}->Delete(
        TABLE   => "Categories",
        KEYS    => [@CID, @subcategories]
      )
    ) || &Error::Error("CP", MESSAGE => "Error deleting records. $in{'DB'}->{'ERROR'}");
    
    if (scalar(@resources) >= 1) {
      (
        $in{'DB'}->Delete(
          TABLE   => "Resources",
          KEYS    => \@resources
        )
      ) || &Error::Error("CP", MESSAGE => "Error deleting records. $in{'DB'}->{'ERROR'}");
    }

    if (scalar(@rates) >= 1) {
      (
        $in{'DB'}->Delete(
          TABLE   => "Rates",
          KEYS    => \@rates
        )
      ) || &Error::Error("CP", MESSAGE => "Error deleting records. $in{'DB'}->{'ERROR'}");
    }

    if (scalar(@reviews) >= 1) {
      (
        $in{'DB'}->Delete(
          TABLE   => "Reviews",
          KEYS    => \@reviews
        )
      ) || &Error::Error("CP", MESSAGE => "Error deleting records. $in{'DB'}->{'ERROR'}");
    }
    
    $StaticPages->Remove(TYPE => "Category", KEYS => \@subcategories)
      || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
    $StaticPages->Remove(TYPE => "Detail", KEYS => \@resources)
      || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");
  }

  $StaticPages->Remove(TYPE => "Category", KEYS => \@CID)
    || &Error::Error("CP", MESSAGE => "Error updating static pages. $StaticPages->{'ERROR'}");

  #----------------------------------------------------------------------#
  # Printing page...                                                     #

  my $Skin = Skin::CP::RemoveCategories->new();

  &Standard::PrintHTMLHeader();
  print $Skin->do();
  
  return 1;
}

1;